package com.dlc.shop.api.controller;

import cn.hutool.core.collection.CollUtil;
import com.dlc.shop.bean.app.dto.ApiProdDto;
import com.dlc.shop.bean.enums.ProdType;
import com.dlc.shop.bean.model.Category;
import com.dlc.shop.bean.param.EsProductParam;
import com.dlc.shop.bean.vo.search.EsProductSearchVO;
import com.dlc.shop.bean.vo.search.ProductSearchVO;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.EsPageVO;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.search.common.param.EsPageParam;
import com.dlc.shop.search.common.service.SearchProductService;
import com.dlc.shop.security.api.util.SecurityUtils;
import com.dlc.shop.service.CategoryService;
import com.dlc.shop.service.ProdBrowseLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 登录情况下的商品推荐接口
 *
 * @author chiley
 * @date 2022/9/21 10:33
 */
@RestController
@RequestMapping("/p/prod")
@Tag(name = "商品推荐接口")
@AllArgsConstructor
public class ProdRecommendController {

    private final CategoryService categoryService;
    private final SearchProductService searchProductService;
    private final ProdBrowseLogService prodBrowseLogService;

    @GetMapping("/recommendList")
    @Operation(summary = "推荐商品列表" , description = "根据商品ID（prodId）获取商品信息")
    public ServerResponseEntity<EsPageVO<EsProductSearchVO>> recommendList(PageParam page,ApiProdDto apiProdDto) {
        String userId = SecurityUtils.getUser().getUserId();
        EsProductParam esProductParam = new EsProductParam();
        if (Objects.isNull(apiProdDto.getProdType())) {
            esProductParam.setProdType(ProdType.PROD_TYPE_NORMAL.value());
        }
        Long primaryCategoryId;
        primaryCategoryId = prodBrowseLogService.recommendCategoryId(apiProdDto.getProdType(), userId);

        // 已登陆但还没有数据，或未登陆
        boolean subCategoryId = (!Objects.equals(apiProdDto.getProdType(), ProdType.PROD_TYPE_SCORE.value()) && Objects.isNull(primaryCategoryId)) && Objects.nonNull(apiProdDto.getCategoryId());
        if (subCategoryId) {
            List<Category> categoryList = categoryService.getCategoryAndParent(apiProdDto.getCategoryId());
            if (CollUtil.isNotEmpty(categoryList)) {
                primaryCategoryId = categoryList.get(0).getCategoryId();
            }
        }
        esProductParam.setPrimaryCategoryId(primaryCategoryId);
        //如果有商品id则过滤掉
        if (Objects.nonNull(apiProdDto.getProdId())) {
            List<Long> prodIds = new ArrayList<>();
            prodIds.add(apiProdDto.getProdId());
            esProductParam.setSpuIdsExclude(prodIds);
        }
        EsPageParam esPageParam = new EsPageParam();
        esPageParam.setCurrent((int) page.getCurrent());
        esPageParam.setSize((int) page.getSize());
        EsPageVO<EsProductSearchVO> productPage = searchProductService.page(esPageParam, esProductParam, Boolean.FALSE);
        List<ProductSearchVO> products = productPage.getRecords().get(0).getProducts();
        long current = page.getCurrent();
        long size = page.getSize();
        int spuNum = products.size();
        // 推荐商品的数量不足时，查询额外的商品进行填充
        if (Objects.equals(current, 1L) && size > spuNum) {
            esPageParam.setSize(Math.toIntExact(size - spuNum));
            esPageParam.setCurrent(1);
            // 查询该分类以外的商品
            esProductParam.setPrimaryCategoryId(null);
            esProductParam.setNotPrimaryCategoryId(primaryCategoryId);
            EsPageVO<EsProductSearchVO> subProductPage = searchProductService.page(esPageParam, esProductParam, Boolean.FALSE);
            for (EsProductSearchVO productSearchVO : subProductPage.getRecords()) {
                if (CollUtil.isNotEmpty(productSearchVO.getProducts())) {
                    products.addAll(productSearchVO.getProducts());
                }
            }
            productPage.setTotal((long) products.size());
            productPage.setPages(productPage.getTotal() > 0 ? (int) page.getCurrent() : 0);
        }
        return ServerResponseEntity.success(productPage);
    }
}
